define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config,
        method = app.method;
    var $category_item_wrp = $("div.category_item_wrp");
    if (window.category) {
        window.category.automatic = true;
    };

    if ($category_item_wrp.length > 0) {
        var sumt = $('button[type="submit"]');
        var $cts = $('[data-toggle="category"]');
        var li_tmp = require("./template/category.html");
        var add_goods_path = config.empty;
        var category = function(element) {
            this.element = element;
            this.category_items = this.element.find("ul.category_items")
            this.data = null;
            var self = this;
            $(".input_search", this.element).on("keyup propertychange", function(e) {
                self.search($(this).val().trim());
            })
        }
        category.prototype.init = function(data, callback) {
            this.data = data;
            this.childs(data, this);
            callback()
            if (window.category.selected) {
                var currthis = $('li[wid="{0}"] a'.format(window.category.selected[0]), this.element);
                if (currthis.length > 0) {
                    currthis.trigger("click", this);
                    currthis.closest('ul').scrollTop(currthis.position().top - 100)
                    return true;
                };
            };
        }
        category.prototype.search = function(t) {
            this.category_items.find('li').each(function() {
                var $this = $(this);
                $this.text().indexOf(t) > -1 ? $this.show() : $this.hide();
            });
        }
        category.prototype.childs = function(data, obj) {
            if (data && data.length > 0) {
                var items_html = new StringBuilder();
                $.each(data, function(index, item) {
                    items_html.Append(li_tmp.format(item.key, item.val,window.category.pageurl.format(item.key)))
                })
                this.category_items.html(items_html.toString());
                obj.show();
                if (window.category.selected && window.category.automatic) {
                    for (var i = 1; i < window.category.selected.length; i++) {
                        var currthis = $('li[wid="{0}"] a'.format(window.category.selected[i]), this.element);
                        if (currthis.length > 0) {
                            currthis.trigger("click")
                            currthis.closest('ul').scrollTop(currthis.position().top - 100)
                            return true;
                        };
                    }

                };
            } else {
                sumt.removeAttr("disabled");
                add_goods_path = sumt.data("remote").format($(".category_item_wrp:visible .selected").last().find("a").data("id"))
            }

        }
        category.prototype.hide = function() {
            this.element.hide()
        }
        category.prototype.show = function() {
            this.element.show();
        }
        category.prototype.text = function() {
            return $(".selected", this.category_items).text();
        }
        var getTxt = function() {
            var sp = [];
            var slecteds = $(".category_item_wrp:visible .selected");
            $.each(slecteds, function() {
                sp.push($(this).text())
            });
            $(".js_selected_text").html(sp.join(">"))
        }

        var level = new Array();
        $.each($cts, function(index, item) {
            level.push(new category($(item)))
        });
        var nextall = level.slice(1);
        level[0].init(window.category.data, function() {
            $("li a", level[0].category_items).on("click", function(e, d) {
                var $this = $(this),
                    id = $this.data('id');
                $this.parent().addClass("selected").siblings().removeClass("selected");
                for (var i = nextall.length - 1; i >= 0; i--) {
                    nextall[i].hide()
                };
                getTxt();
                sumt.attr("disabled", "disabled");
                method.get(window.category.url.format(id), function(d) {
                    level[1].childs(d, level[1]);
                })
                if (!d) {
                    window.category.automatic = false;
                };
                isAddCategory();
            });

        });
        for (var i = 1; i < level.length; i++) {
            level[i].element.attr("index", i);
            $(level[i].category_items).on("click", "li a", function() {
                var $this = $(this),
                    id = $this.data('id'),
                    item_wrp = $this.parents("div.category_item_wrp"),
                    next_item = item_wrp.next();
                var index = next_item.attr("index");
                $this.parent().addClass("selected").siblings().removeClass("selected");
                item_wrp.nextAll().hide();
                getTxt();
                sumt.attr("disabled", "disabled");
                if (level[index]) {
                    method.get(window.category.url.format(id), function(d) {
                        level[index].childs(d, next_item)
                    });
                } else {
                    sumt.removeAttr("disabled");
                    add_goods_path = sumt.data("remote").format($(".category_item_wrp:visible .selected").last().find("a").data("id"));
                    
                }
                isAddCategory();

            })

        };

        sumt.on("click", function() {
            add_goods_path.length > 0 && config.msg.redirect(add_goods_path);
        })



    };
    function isAddCategory(){
        var selectcate=getCategorys();
        var flag=$.inArray(selectcate.selectid, existCategorys());
        if(flag>-1){
            categorybtn(false,true);
        }else{
            categorybtn(true,false);
        }
    }
    $(document).on("click",".js_add_common_category",function(){
        var $this=$(this),path=$this.data("path"),selectcate=getCategorys(),
        $js_category_lsit_div=$(".js_category_lsit_div"),
        $ul=$js_category_lsit_div.find("ul.category-dropdown-select");
        if(path){
            method.post(path, function(data) {
                if (config.issucceed(data)) {
                    $js_category_lsit_div.find("span.category-dropdown-label").html(selectcate.selectname);
                    $ul.find("li").removeClass('active');
                    $(template("js_addcategory_temp",{
                        "id": selectcate.selectid,
                        "name": selectcate.selectname
                    })).insertAfter($ul.find("li:first"));
                    config.msg.info(data.message || config.lang.saveSuccess);
                    categorybtn(false,true);
                } else {
                    config.msg.error(data.message);
                }

            }, "网络错误", false, {
                "id": selectcate.selectid,
                "name": selectcate.selectname
            });
        }
    });
    $(document).on("click",".js_category_del",function(){
        var $this=$(this),path=$this.data("path"),
        $js_category_lsit_div=$(".js_category_lsit_div"),
        $li=$this.closest('li'),id=$li.data("id");
        if(path){
            method.post(path, function(data) {
                if (config.issucceed(data)) {
                    if($li.hasClass("active")){
                        $js_category_lsit_div.find("span.category-dropdown-label").html("选择常用类目");
                        categorybtn(true,false);
                    }
                    $li.remove();
                    config.msg.info(data.message || config.lang.removeSuccess);
                } else {
                    config.msg.error(data.message);
                }

            }, "网络错误", false, {
                "id": id
            });
        }
    });
    function categorybtn(addbtn,exist){
        var $js_add_common_category = $(".js_add_common_category");
        var $js_used_category = $(".js_used_category");
        if(addbtn){
            $js_add_common_category.removeClass('hide');
        }else{
            $js_add_common_category.addClass('hide');
        }
        if(exist){
            $js_used_category.removeClass('hide');
        }else{
            $js_used_category.addClass('hide');
        }
    }
    function getCategorys(){
        var selectid="",selectname="",arrid=[],arrtext=[];
        $(".category_item_wrp").each(function(){
            var $this=$(this),$select=$this.find("li.selected");
            if(!$this.is(":hidden")){
                if($select.attr("wid")){
                    arrid.push($select.attr("wid"));
                    arrtext.push($select.find("a").attr("title"));
                }
                
            }
        });
        selectid=arrid.join(",");
        selectname=arrtext.join(">");
        return {
            selectid:selectid,
            selectname:selectname
        }
    }
    function existCategorys(){
        var $js_category_lsit_div=$(".js_category_lsit_div"),ids=[];
        $js_category_lsit_div.find("ul.category-dropdown-select li").each(function(){
            var id=$(this).data("id");
            if(id){
                ids.push(id+"");
            }
        });
        return ids;
    }

});